package org.lanplay.server.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import org.lanplay.server.model.Game;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class GameDao implements Serializable {
	private static final long serialVersionUID = 1L;

	@Inject
	private Provider<EntityManager> emp;

	@SuppressWarnings("unchecked")
	public List<Game> getGamesList() {
		return emp.get()
				.createQuery("SELECT g from Game g order by g.name asc")
				.getResultList();

	}

	public boolean save(Game game) {
		boolean alreadyPersisted = game.getId() != null;
		try {
			emp.get().persist(game);
			emp.get().flush();
			return true;
		} catch (PersistenceException e) {
			if (!alreadyPersisted) {
				game.setId(null);
			}
			emp.get().clear();
			return false;
		}
	}
}
